import { useEffect, useState, useRef } from "react";
export const useFetch = (url, config?, callback?) => {
  const fetching = useRef(false);
  const [refresh, setRefresh] = useState(0);
  const { data, headers, method, aborter, query } = config || {};
  const [res, setRes] = useState<[any, string] | []>([]);

  if (query) {
    url += "?" + new URLSearchParams(query).toString();
  }

  const abortConf = aborter ? { signal: aborter.signal } : {};
  const fetchConf = {
    method: method || "GET",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${localStorage.getItem("token")}` || "",
      ...headers,
    },
    ...abortConf,
  };

  useEffect(() => {
    if (typeof callback === "function" && !callback()) return;
    setRes([undefined, url]);
    fetching.current = true;
    fetch(import.meta.env.VITE_SERVER_ADDRESS + url, fetchConf)
      .then((res) => res.json())
      .then((res) => {
        if (res.status === 1) {
          setRes([res.data, url]);
        }
        fetching.current = false;
      })
      .finally(() => {
        // console.log(url, "fetch end");
      });

    return () => {
      if (aborter && fetching.current) {
        fetching.current = false;
        aborter.abort("url aborted: " + url);
      }
    };
  }, [url, refresh]);

  return {
    res: res[0],
    url: res[1],
    refresh: () => setRefresh(1 - refresh),
  };
};


export const useInput: () => (string | ((e: any) => void))[] = () => {
  const [value, setValue] = useState('')
  const handleChange = (e) => {
    setValue(e.target.value)
  }

  return [value, handleChange]
}